package com.datamation.swadeshi.view;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.GPSTracker;
import com.datamation.swadeshi.listviewitems.ChartItem;
import com.datamation.swadeshi.listviewitems.LineChartItem;
import com.datamation.swadeshi.listviewitems.PieChartItem;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

@SuppressLint("NewApi")
public class DashboardFragment extends Fragment {

	// dashboard variables
	ListView lv_dashboard;
	ChartDataAdapter cda;
	ArrayList<ChartItem> list;
	GPSTracker gps;
	// Refresh menu item
	private MenuItem refreshMenuItem;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.dash_board, container, false);
		GPSTracker gps = new GPSTracker(getActivity());
		if(gps.canGetLocation())
		{
			
		}
		else
		{
			gps.showSettingsAlert();
		}

		getActivity().getActionBar().removeAllTabs();
		getActivity().getActionBar().setNavigationMode(0);
		setHasOptionsMenu(true);

		SetTitleAdapter adapter =new SetTitleAdapter();
		adapter.createCutomActionBarTitle("Dashboard", getActivity());

		// dashboard
		lv_dashboard = (ListView) rootView.findViewById(R.id.listView1);
		list = new ArrayList<ChartItem>();

		// line chart
		list.add(new LineChartItem(generateDataLine(1 + 1), getActivity()
				.getApplicationContext()));
		// pie chart
		list.add(new PieChartItem(generateDataPie(2 + 1), getActivity()
				.getApplicationContext()));

		cda = new ChartDataAdapter(getActivity().getApplicationContext(), list);
		// set dashboard
		lv_dashboard.setAdapter(cda);



		
		//back button disable 
		rootView.setFocusableInTouchMode(true);
		rootView.requestFocus();
		rootView.setOnKeyListener(new View.OnKeyListener() {
		        @Override
		        public boolean onKey(View v, int keyCode, KeyEvent event) {
		            Log.i("", "keyCode: " + keyCode);
		            if( keyCode == KeyEvent.KEYCODE_BACK ) {
		            	Toast.makeText(getActivity(),"Back Navigationid is disable", Toast.LENGTH_SHORT).show();
		               // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
		                return true;
		            }else if ((keyCode == KeyEvent.KEYCODE_HOME)) {
		    			
		    			getActivity().finish();
		    			
		    			return true;

		    		} else {
		                return false;
		            }
		        }
		    });
		
		return rootView;
	}

	
	
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		for (int i = 0; i < menu.size(); ++i) {
			menu.removeItem(menu.getItem(i).getItemId());
		}
		inflater.inflate(R.menu.act_main, menu);
		// getActivity().getActionBar().setTitle("SR Performance");
		// getActivity().getActionBar().setBackgroundDrawable(new
		// ColorDrawable(Color.parseColor("#288dab")));
		super.onCreateOptionsMenu(menu, inflater);
	}

	// MenuItem refreshMenuItem = (MenuItem)
	// menu.findItem(R.id.action_refresh).getActionView();
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		case R.id.action_refresh:
			// refresh
			refreshMenuItem = item;
			// Refresh dashBoard
			new RefreshData().execute();

			return true;

		case R.id.action_settings:
			// refresh
			refreshMenuItem = item;
			Intent mainActivity = new Intent(getActivity()
					.getApplicationContext(), SettingsActivity.class);
			startActivity(mainActivity);

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Async task to load the data from server
	 * **/
	private class RefreshData extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			// set the progress bar view
			refreshMenuItem.setActionView(R.layout.action_progressbar);

			refreshMenuItem.expandActionView();
		}

		@Override
		protected String doInBackground(String... params) {
			// not making real request in this demo
			// for now we use a timer to wait for sometime
			try {
				list.clear();
				// line chart
				list.add(new LineChartItem(generateDataLine(1 + 1),
						getActivity().getApplicationContext()));
				// pie chart
				list.add(new PieChartItem(generateDataPie(2 + 1), getActivity()
						.getApplicationContext()));

				cda = new ChartDataAdapter(getActivity()
						.getApplicationContext(), list);

				Thread.sleep(500);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			refreshMenuItem.collapseActionView();
			lv_dashboard.clearTextFilter();
			// set dashboard
			lv_dashboard.setAdapter(cda);

			// remove the progress bar view
			refreshMenuItem.setActionView(null);

		}
	};

	private LineData generateDataLine(int cnt) {

		ArrayList<Entry> e1 = new ArrayList<Entry>();

		for (int i = 0; i < 12; i++)// month
		{
			e1.add(new Entry((int) (Math.random() * 65) + 40, i));
		}

		LineDataSet d1 = new LineDataSet(e1, "Target sales");
		d1.setLineWidth(3f);
		d1.setCircleSize(5f);
		d1.setHighLightColor(Color.parseColor("#336699"));

		ArrayList<Entry> e2 = new ArrayList<Entry>();

		for (int i = 0; i < 12; i++) {
			e2.add(new Entry(e1.get(i).getVal() - 30, i));
		}

		LineDataSet d2 = new LineDataSet(e2, "Actual sales");
		d2.setLineWidth(3f);
		d2.setCircleSize(5f);
		d2.setHighLightColor(Color.rgb(244, 117, 117));
		d2.setColor(ColorTemplate.VORDIPLOM_COLORS[0]);
		d2.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[0]);

		ArrayList<LineDataSet> sets = new ArrayList<LineDataSet>();
		sets.add(d1);
		sets.add(d2);

		LineData cd = new LineData(getMonths(), sets);
		return cd;
	}

	private ArrayList<String> getMonths() {

		ArrayList<String> m = new ArrayList<String>();
		m.add("Jan");
		m.add("Feb");
		m.add("Mar");
		m.add("Apr");
		m.add("May");
		m.add("Jun");
		m.add("Jul");
		m.add("Aug");
		m.add("Sep");
		m.add("Okt");
		m.add("Nov");
		m.add("Dec");

		return m;
	}

	private class ChartDataAdapter extends ArrayAdapter<ChartItem> {

		public ChartDataAdapter(Context context, List<ChartItem> objects) {
			super(context, 0, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getItem(position).getView(position, convertView,
					getContext());
		}

		@Override
		public int getItemViewType(int position) {
			// return the views type
			return getItem(position).getItemType();
		}

		@Override
		public int getViewTypeCount() {
			return 3; // we have 3 different item-types
		}
	}

	private PieData generateDataPie(int cnt) {

		ArrayList<Entry> entries = new ArrayList<Entry>();

		for (int i = 0; i < 4; i++) {
			entries.add(new Entry((int) (Math.random() * 70) + 30, i));
		}

		PieDataSet d = new PieDataSet(entries, "");

		// space between slices
		d.setSliceSpace(5f);
		d.setColors(ColorTemplate.PASTEL_COLORS);

		PieData cd = new PieData(getQuarters(), d);
		return cd;
	}

	private ArrayList<String> getQuarters() {

		ArrayList<String> q = new ArrayList<String>();
		q.add("1st Quarter");
		q.add("2nd Quarter");
		q.add("3rd Quarter");
		q.add("4th Quarter");

		return q;
	}


}
